package com.hollowlatte.manage.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hollowlatte.common.utils.Result;
import com.hollowlatte.manage.entity.Role;
import com.hollowlatte.manage.entity.vo.PermsVO;
import com.hollowlatte.manage.entity.vo.RoleVO;
import com.hollowlatte.manage.service.RoleService;
import com.hollowlatte.manage.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Hollow Latte
 * @since 2021-04-27
 */
@RequiresRoles("admin")
@Tag(name = "RoleController", description = "角色管理")
@CrossOrigin
@RestController
@RequestMapping("/role")
public class RoleController {
    private final RoleService roleService;

    private final UserService userService;

    public RoleController(RoleService roleService, UserService userService) {
        this.roleService = roleService;
        this.userService = userService;
    }


    @Operation(summary = "添加角色并分配权限", description = "传入角色名和权限列表即可，若权限列表为null，则仅添加角色")
    @PostMapping()
    public Result addRoleAndAssignPerms(@RequestBody RoleVO roleVO) {
        List<PermsVO> permsVOList = roleVO.getPermsList();

        Role role = new Role();
        role.setName(roleVO.getName());
        boolean affect = roleService.save(role);
        System.out.println(role);
        if (!CollectionUtils.isEmpty(permsVOList)) {
            List<Long> permsIdList = permsVOList.stream().map(PermsVO::getId).collect(Collectors.toList());

            for (Long permsId : permsIdList) {
                affect = roleService.assignPermsForRole(role.getId(), permsId);
            }
        }

        if (affect) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }


    @Operation(summary = "为角色并分配权限")
    @PostMapping("perms")
    public Result assignPermsForRole(@RequestBody RoleVO roleVO) {
        List<PermsVO> permsVOList = roleVO.getPermsList();
        boolean affect = false;
        if (!CollectionUtils.isEmpty(permsVOList)) {
            List<Long> permsIdList = permsVOList.stream().map(PermsVO::getId).collect(Collectors.toList());
            for (Long permsId : permsIdList) {
                affect = roleService.assignPermsForRole(roleVO.getId(), permsId);
            }
        }

        if (affect) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }


    @Operation(summary = "删除角色并清除分配给该角色的所有权限")
    @DeleteMapping()
    public Result deleteRole(@RequestParam Long roleId) {
        boolean affect = roleService.removeRole(roleId);

        if (affect) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }


    @Operation(summary = "删除角色指定的权限")
    @DeleteMapping("perms")
    public Result deletePermsOfRole(@RequestBody RoleVO roleVO) {
        List<PermsVO> permsVOList = roleVO.getPermsList();
        boolean affect = false;
        if (!CollectionUtils.isEmpty(permsVOList)) {
            List<Long> permsIdList = permsVOList.stream().map(PermsVO::getId).collect(Collectors.toList());
            for (Long permsId : permsIdList) {
                affect = roleService.removePermsOfRole(roleVO.getId(), permsId);
            }
        }

        if (affect) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }


    @Operation(summary = "根据id修改角色名")
    @PutMapping()
    public Result modifyRole(@RequestBody RoleVO roleVO) {
        Role role = new Role();
        BeanUtils.copyProperties(roleVO, role);

        boolean affect = roleService.updateById(role);

        if (affect) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }


    @Operation(summary = "根据id修改角色的权限")
    @PutMapping("perms")
    public Result modifyPermsForRole(@RequestBody RoleVO roleVO) {
        List<PermsVO> newPermsList = roleVO.getPermsList();
        List<Long> newPermsIdList = newPermsList.stream().map(PermsVO::getId).collect(Collectors.toList());
        boolean affect = false;
        if (!CollectionUtils.isEmpty(newPermsList)) {
            affect = roleService.updatePermsForRole(roleVO.getId(), newPermsIdList);
        }

        if (affect) {
            return Result.ok();
        } else {
            return Result.error();
        }
    }


    @Operation(summary = "通过id查角色")
    @GetMapping()
    public Result findByUserId(@RequestParam Long userId) {
        List<Role> roleList = userService.listRoleById(userId);

        List<RoleVO> roleVOList = roleService.convertRoleToRoleVO(roleList);

        return Result.ok().data("roleList", roleVOList);
    }


    @Operation(summary = "分页查询")
    @GetMapping("pagination")
    public Result paging(@RequestParam Long current, @RequestParam Long size) {
        Page<Role> rolePage = new Page<>(current, size);
        roleService.page(rolePage);

        Page<RoleVO> roleVOPage = new Page<>(current, size);
        BeanUtils.copyProperties(rolePage, roleVOPage);

        roleVOPage.setRecords(roleService.convertRoleToRoleVO(rolePage.getRecords()));

        return Result.ok().data("pageInfo", roleVOPage);
    }
}

